<template>
  <view class="store-item">
    <image :src="icon" class="uni-image-top"></image>
    <picker
        mode="multiSelector"
        @columnchange="onColumnChange"
        @change="onPickerConfirm"
        :value="currentIndex"
        :range="displayColumns"
        :disabled="disabled"
        range-key="label"
        class="picker"
    >
      <view class="uni-input">
        {{ selectedLabels.join('/') || placeholder }}
        <uni-icons type="arrowright" size="18" color="#999"></uni-icons>
      </view>
    </picker>
  </view>
</template>

<script>


import UniIcons from "../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import {getAction} from "../utils/action";

export default {
  name: "aDataPicker",
  model: {
    prop: "modelValue",
    event: "update:modelValue"
  },
  components: {UniIcons},
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    modelValue: Array,
    url: String,
    urlChild: String,
    icon: String,
    dictCode: String,
    placeholder: {
      type: String,
      default: '请选择'
    },
    // 数据加载方式：static-静态字典 / dynamic-动态接口
    loadType: {
      type: String,
      default: 'static'
    }
  },
  data() {
    return {
      currentIndex: [],        // 当前各列选中索引
      columnData: [],          // 完整层级数据
      displayColumns: [],      // 当前显示的列数据
      dataSource: [],
      selectedModel: {}
    }
  },
  async mounted() {
    await this.initData()
  },
  watch: {
    modelValue: {
      async handler(newVal) {
        await this.initData()
        this.findValueInColumns(newVal);
      },
      deep: true,
      immediate: true,
    }
  },
  methods: {
    async initData() {
      try {
        // 获取初始数据
        let res = await getAction(this.url + "&classifyType=2")
        if (res.result) {
          this.dataSource = this.normalizeData(res.result)
          // 初始化三列数据（带兜底）
          this.displayColumns = [
            this.normalizeData(this.dataSource[0]?.children || []),
            this.normalizeData(this.dataSource[0]?.children?.[0]?.childList || [])
          ];
        }
      } catch (e) {
        console.error('数据加载失败', e)
      }
    },
    // 标准化数据结构
    normalizeData(data) {
      return data.map(item => ({
        label: item.title || item.classifyName,
        value: item.cvalue || item.id,
        parentId: item.parentId,
        children: item.childList || []
      }))
    },
    // 列变化事件
    onColumnChange(e) {
      const {column, value} = e.detail
      if (column == 0) {
        this.currentIndex = [[value], [0]]
        this.displayColumns[1] = this.normalizeData(this.displayColumns[column][value].children)
        this.selectedModel = [this.displayColumns[1][0]]
      } else {
        this.selectedModel = [this.displayColumns[column][value]]
        this.currentIndex = [this.currentIndex[0], [value]]
      }
      this.$emit('update:modelValue', this.selectedModel)
    },
    // 确认选择
    onPickerConfirm(e) {
      if (this.displayColumns[0] && this.currentIndex && this.displayColumns[0].length == 0 && this.currentIndex.length == 0) {
        return
      }
      if (!this.currentIndex || this.currentIndex.length == 0) {
        this.displayColumns[1] = this.normalizeData(this.displayColumns[0][0].children)
        this.selectedModel = [this.displayColumns[1][0]]
        this.currentIndex = [[0], [0]]
      }
      this.$emit('update:modelValue', this.selectedModel)
      this.$emit('change', this.selectedModel)
    },
    findValueInColumns(value) {
      let noe = this.displayColumns[0].filter(item => item.value === value[0].parentId).map((item, index) => ({
        item,
        index
      }))
      let two = this.displayColumns[1].filter(item => item.value === value[0].value).map((item, index) => ({
        item,
        index
      }))
      if (noe.length > 0 && two.length > 0) {
        this.currentIndex = [noe[0].index, two[0].index]
        this.displayColumns = [[noe[0].item], [two[0].item]]
      }
    }
  },
  computed: {
    selectedLabels() {
      return this.currentIndex.map((index, i) =>
          this.displayColumns[i][index]?.label || ''
      )
    }
  }
}
</script>

<style scoped lang="scss">
.store-item {
  width: 100%;
  display: flex;
  text-align: right;
  align-items: center;

  .uni-image-top {
    width: 40rpx;
    height: 40rpx;
    margin-right: 20rpx;
  }

  .picker {
    flex: 1;

    .uni-input {
      width: 100%;
      text-align: right;
      font-size: 28rpx;
      color: #999;

      &:after {
        content: '';
        display: inline-block;
        width: 12rpx;
        height: 12rpx;
        border-radius: 50%;
        margin-left: 10rpx;
        opacity: 0.6;
      }

      font {
        font-weight: 500;
      }

      & > uni-icons {
        color: #999;
        font-size: 36rpx;
        transform: scale(1.5);
      }
    }
  }
}
</style>
